import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, getRequestToken, checkNotAuth, checkUserNotFound } from '@/utils/auth'
import { checkForbidden } from './auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout 10s
})

// request interceptor
service.interceptors.request.use(
  config => {
    // 将用户类型加入请求头
    config.headers['User-Type'] = 1

    // do something before request is sent
    const accessToken = getToken()

    if (accessToken) {
      // Authorization 前后端统一的认证头
      config.headers['Authorization'] = getRequestToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      const code = res.code
      codeMessage(code, res)
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    const res = error.data
    const code = res.code
    codeMessage(code)
    return Promise.reject(error)
  }
)

function codeMessage(code, res) {
  if (checkNotAuth(code) === true) {
    MessageBox.confirm('登录已失效，您可以取消并停留当前页面，或者重新登录', '确认退出登录', {
      confirmButtonText: '重新登录',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      store.dispatch('user/resetToken').then(() => {
        location.reload()
      })
    })
  } else if (checkForbidden(code) === true) {
    Message({
      message: '您没有权限访问资源',
      type: 'error',
      duration: 5 * 1000
    })

    this.$router.push({
      name: '401'
    })
  } else if (checkUserNotFound(code) === true) {
    Message({
      message: '登录失败',
      type: 'error',
      duration: 5 * 1000
    })
  } else {
    Message({
      message: res.message || 'Error',
      type: 'error',
      duration: 5 * 1000
    })
  }
}

export default service
